package org.warm.meaning.x.base.util.bean;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

public class FieldUtil {

    public static final String SET_METHOD = "set";
    public static final String GET_METHOD = "get";

    public static FieldUtil build() {
        return new FieldUtil();
    }

    /**
     * 递归获取所有字段
     * 包括父类的字段
     *
     * @param clazz 类
     * @return 类所有字段及父类字段
     */
    public List<Field> getAllField(Class<?> clazz) {
        if (null == clazz) {
            return new ArrayList<>(0);
        }
        if (clazz.getName().startsWith("java.lang") || clazz.getName().startsWith("java.math")) {
            return new ArrayList<>(0);
        }
        // 获取字段
        Field[] fields = clazz.getDeclaredFields();
        List<Field> fieldList = Arrays.stream(fields).collect(Collectors.toList());
        Set<String> fieldNameSet = fieldList.stream().map(Field::getName).collect(Collectors.toSet());

        Class<?> superClazz = clazz.getSuperclass();
        if (null != superClazz) {
            // 获取父类字段
            List<Field> superClazzFields = getAllField(superClazz);
            if (null != superClazzFields && !superClazzFields.isEmpty()) {
                fieldList.addAll(superClazzFields.stream().filter(superField -> !fieldNameSet.contains(superField.getName())).toList());
            }
        }
        return fieldList;
    }

}
